package com.hsy.sunflowerbao.common.ui

import android.Manifest
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Message
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView

import com.hsy.sunflowerbao.R
import com.hsy.sunflowerbao.base.ui.activity.BaseActivity
import com.hsy.sunflowerbao.home.ui.HomeFragment
import com.hsy.sunflowerbao.common.store.MainStore
import com.hsy.sunflowerbao.home.ui.ScanActivity
import com.hsy.sunflowerbao.message.ui.MessageFragment

import kotlinx.android.synthetic.main.activity_main.*
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.OnNeverAskAgain
import permissions.dispatcher.OnPermissionDenied
import permissions.dispatcher.RuntimePermissions

/**
 * 主Activity
 * Created on 2018/3/26.
 *
 * @author yang
 */
@RuntimePermissions
class MainActivity : BaseActivity<MainStore>() {

    /**
     * 数据缓存器
     */
    override var store = MainStore(dispatcher)

    /**
     * Tab对应的Fragment
     */
    private val fragments = arrayOf(HomeFragment::class.java, MessageFragment::class.java)
    /**
     * Tab显示的文字
     */
    private val fragmentsNames = arrayOf("首页", "消息")
    /**
     * Tab显示的图标
     */
    private val icons = intArrayOf(R.drawable.navigation_home, R.drawable.navigation_message)

    /**
     * 添加TabItem
     * @param index Tab索引
     */
    private fun getTabItem(index: Int): View {
        val view = LayoutInflater.from(this).inflate(R.layout.tab_indicator, null)
        val tabImg: ImageView = view.findViewById(R.id.tab_img)
        val text: TextView = view.findViewById(R.id.tab_text)
        tabImg.setImageResource(icons[index])
        text.text = fragmentsNames[index]
        return view
    }

    private var isMy = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tabs.setup(this, supportFragmentManager, R.id.container)

        for (i in fragments.indices) {
            val tabSpec = tabs.newTabSpec(fragmentsNames[i])
            tabSpec.setIndicator(getTabItem(i))
            tabs.addTab(tabSpec, fragments[i], null)
        }
        tabs.tabWidget.showDividers = LinearLayout.SHOW_DIVIDER_NONE
        tabs.setOnTabChangedListener { tabId ->
            if (tabId == fragmentsNames[1] != isMy) {
                isMy = tabId == fragmentsNames[1]
            }
        }
        tabs.currentTab = 0
        //检查版本更新
        //        new VersionChecker(this).check();
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (KeyEvent.ACTION_UP == event.action && KeyEvent.KEYCODE_BACK == event.keyCode) {
            exit()
            return true
        }
        return super.dispatchKeyEvent(event)
    }

    private var isExit = false

    public override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        isExit = false
    }

    /**
     * 退出事件
     */
    private fun exit() {
        if (!isExit) {
            isExit = true
            showToast(R.string.msg_exit)
            // 利用handler延迟发送更改状态信息
            sendEmptyMessageDelayed(0, 2000)
        } else finish()
    }

    /**
     * 调用相机拍照
     */
    @NeedsPermission(Manifest.permission.CAMERA)
    fun startScan() {
        startActivity(ScanActivity::class.java)
    }

    /**
     * 获取相机权限失败
     */
    @OnPermissionDenied(Manifest.permission.CAMERA)
    internal fun showDeniedForCamera() {
        showToast(getString(R.string.permission_denied, "相机"))
    }

    /**
     * 禁止再次获取相机权限
     */
    @OnNeverAskAgain(Manifest.permission.CAMERA)
    internal fun showNeverAskForCamera() {
        showToast(getString(R.string.permission_no_ask, "相机"))
    }

    /**
     * 权限获取结果
     *
     * @param requestCode  请求码
     * @param permissions  申请的权限
     * @param grantResults 结果
     */
    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)
    }
}